package com.hmkj.core.service.wx.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hmkj.common.utils.HttpClientUtils;
import com.hmkj.common.utils.JsonUtils;
import org.apache.log4j.Logger;

import java.util.HashMap;

/**
 * 微信公众号设置同步微信服务器相关接口
 *
 * @author Vector
 * @create 2017-06-15 22:22
 */
public class WeixinCore {

    protected static final Logger logger = Logger.getLogger(WeixinCore.class);

    /**
     * 获取微信公众号接口accessToken
     * @param appid
     * @param secret
     * @param wxId
     * @return
     * @throws Exception
     */
    public static String getMpApiAccessToken(String appid, String secret, int wxId) throws Exception{
        if (appid==null || appid.length()<=0) {
            logger.info("weixinapi:无效appid");
            throw new Exception("微信公众号接口授权信息无效");
        }
        if (secret==null || secret.length()<=0) {
            logger.info("weixinapi:无效secret");
            throw new Exception("微信公众号接口授权信息无效");
        }
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?"
                +"grant_type=client_credential"
                +"&appid="+ appid
                +"&secret="+ secret;
        logger.info("微信公众号接口：accessTokenUrl值为"+accessTokenUrl);
        String accessTokenJson;
        try{
            accessTokenJson = HttpClientUtils.httpGet(accessTokenUrl, "UTF-8");
            logger.info("微信公众号接口：accessTokenJson值为"+accessTokenJson);
        }catch (Exception e){
            logger.info("weixinapi:"+e.getMessage());
            throw new Exception("微信公众号接口授权失败");
        }
        HashMap<String, Object> accessTokenMap = JsonUtils.toGenericObject(accessTokenJson, new TypeReference<HashMap<String, Object>>() {});
        if (accessTokenMap==null || accessTokenMap.get("access_token")==null || accessTokenMap.get("expires_in")==null) {
            logger.info("微信公众号接口:accessToken获取失败");
            throw new Exception("微信公众号接口授权信息解析失败");
        }
        //保存accesstoken到本地服务器
        String accesstoken = accessTokenMap.get("access_token").toString();
        //weixinAccountDao.updateAccessToken(wxId, accesstoken);
        return accesstoken;
    }
}
